package com.techsoul.module.pms.controller;

import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.pojo.Result;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.poi.ExcelImport;
import com.techsoul.common.log.annotation.Log;
import com.techsoul.common.log.enums.OperationTypeEnum;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.basic.pojo.param.SuspiciousItemSaveParam;
import com.techsoul.module.pms.enmus.WmsOutStatusEnum;
import com.techsoul.module.pms.pojo.entity.TbWmsMaterialDelivery;
import com.techsoul.module.pms.pojo.param.TbWmsMaterialDeliveryLineSaveParam;
import com.techsoul.module.pms.pojo.param.TbWmsMaterialDeliveryLineSearchParam;
import com.techsoul.module.pms.pojo.param.TbWmsMaterialReceiptLineSaveParam;
import com.techsoul.module.pms.pojo.vo.TbWmsMaterialDeliveryLineVo;
import com.techsoul.module.pms.service.ITbWmsMaterialDeliveryLineService;
import com.techsoul.module.pms.service.ITbWmsMaterialReceiptLineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 出库明细 Controller
 *
 * @author liuen
 * @date 2022-01-25
 */
@Api(tags = "出库明细")
@Slf4j
@RestController
@RequestMapping("/web/tbWmsMaterialDeliveryLine")
public class TbWmsMaterialDeliveryLineController {

    @Autowired
    private Result result;
    
    @Autowired
    private ITbWmsMaterialDeliveryLineService service;
    @Autowired
    private ITbWmsMaterialReceiptLineService iTbWmsMaterialReceiptLineService;
    @Autowired
    private TokenService tokenService;

    @ApiOperation("新增")
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:insert')")
    @PostMapping
    public Result insert(@Valid @RequestBody TbWmsMaterialDeliveryLineSaveParam params) {
        return result.success(this.service.insert(params));
    }

    @ApiOperation("批量删除（多个用逗号隔开）")
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:delete')")
    @DeleteMapping("/{ids}")
    public Result batchDelete(@PathVariable String[] ids) {
        return result.success(this.service.batchDelete(Arrays.asList(ids)));
    }
    @ApiOperation("批量生成仓储费结算")
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:generateWarehouseArForDelivery')")
    @PostMapping("/generateWarehouseArForDelivery/{ids}")
    public Result generateWarehouseArForDelivery(@PathVariable String[] ids) {
        return result.success(this.iTbWmsMaterialReceiptLineService.generateWarehouseArForDelivery(Arrays.asList(ids)));
    }
    @ApiOperation("批量生成配送结算")
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:generateArForDelivery')")
    @PostMapping("/generateArForDelivery/{ids}")
    public Result generateArForDelivery(@PathVariable String[] ids) {
        return result.success(this.iTbWmsMaterialReceiptLineService.generateArForDelivery(Arrays.asList(ids)));
    }
    @ApiOperation("确认出库")
   // @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:outbound')")
    @PostMapping("/outbound")
    public Result outbound(@Valid @RequestBody TbWmsMaterialDeliveryLineSaveParam params) {

        params.setStatus(WmsOutStatusEnum.outed.getValue());
        return result.success(this.service.outbound(params));
    }
    @ApiOperation("修改")
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:update')")
    @PutMapping
    public Result update(@Valid @RequestBody TbWmsMaterialDeliveryLineSaveParam params) {
        return result.success(this.service.update(params));
    }

    @ApiOperation("详情")
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:search')")
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") String id) {
        return result.success(this.service.findById(id));
    }

    @ApiOperation("列表")
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:search')")
    @PostMapping("/search")
    public Result findAll(@RequestBody TbWmsMaterialDeliveryLineSearchParam params) {

        return result.success(this.service.findAll(params));
    }
    @ApiOperation("确认")
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:update')")
    @PostMapping("/confirm/{id}")
    public Result confirm(@PathVariable("id") String id) {
        return result.success(this.service.confirm(id));
    }
    @ApiOperation("列表-分页")
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:search')")
    @PostMapping("/search/{current}/{pageSize}")
    public Result findAll(@RequestBody TbWmsMaterialDeliveryLineSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        return result.success(this.service.findAll(params, current, pageSize));
    }

    @ApiOperation("列表-分页")
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:search')")
    @PostMapping("/search1/{current}/{pageSize}")
    public Result findAll1(@RequestBody TbWmsMaterialDeliveryLineSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        return result.success(this.service.findAll1(params, current, pageSize));
    }

    @ApiOperation("移入可疑")
    @Log(title = "移入可疑", operationType = OperationTypeEnum.UPDATE)
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialReceiptLine:update')")
    @PostMapping("/moveToSuspicious")
    public Result moveToSuspicious(@Valid @RequestBody TbWmsMaterialDeliveryLineSaveParam params) {
        return result.success(this.service.moveToSuspicious(params));
    }
    @ApiOperation("计算出库指数")
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:calculateOutboundRate')")
    @PostMapping("/calculateOutboundRate")
    public Result calculateOutboundRate() {
        return result.success(this.service.calculateOutboundRate());
    }
    @ApiOperation("导入")
    @PreAuthorize("hasAnyAuthority('web:tbWmsMaterialDeliveryLine:insert')")
    @PostMapping("/importData")
    public Result importData(MultipartFile file) {
        List<TbWmsMaterialDeliveryLineVo> dataList = null;
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();


        int successNum = 0;
        int failureNum = 0;
        int logNum = 0;
        try {
            ExcelImport excelImport = new ExcelImport(file, 1, 0);
            dataList = excelImport.getDataList(TbWmsMaterialDeliveryLineVo.class);
        } catch (Exception e) {
            log.error("获取数据信息失败!");
            throw new ExcelException("获取数据信息失败!");
        }
        if (ListUtils.isEmpty(dataList)) {
            throw new ExcelException("导入数据不能为空！");
        }

        if(dataList==null||dataList.size()==0){
            //return "没有读取到数据";
            log.error("没有读取到数据!");
        }
        TbWmsMaterialDeliveryLineVo firstTbWmsMaterialDeliveryLineVo = (TbWmsMaterialDeliveryLineVo)dataList.get(0);
        String supplierNo ="";
        TbWmsMaterialDelivery newTbWmsMaterialDelivery = null;
        int itemNo = 0;
        int line = 0;
        List<String> supplierNos = new ArrayList<String>();
        for (TbWmsMaterialDeliveryLineVo data : dataList) {
            successNum++;
            line++;
            newTbWmsMaterialDelivery=   this.service.importData(data,supplierNo,user,itemNo,line, newTbWmsMaterialDelivery);
          //  if (!supplierNos.contains(supplierNo)) {
           //     newTbWmsMaterialDelivery=   this.service.importData(data,supplierNo,user,itemNo,line, newTbWmsMaterialDelivery);

          //      supplierNos.add(supplierNo);
          //  }else{
          //      newTbWmsMaterialDelivery=this.service.importData( data,"No",user,itemNo,line,newTbWmsMaterialDelivery);
          //  }
            itemNo = itemNo++;
        }


        successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");

        return result.success(successMsg.toString());
    }



    @ApiOperation("导入")
    @PostMapping("/importData1")
    public Result importData1(MultipartFile file) {
        return result.success(this.service.importData1(file));
    }
}
